<?php

namespace Admin\Controller;

class TransferController extends AdminbaseController {

    function _initialize() {
        parent::_initialize();
        $this->currentModel = D("Transfer");
    }

    public function index() {
        $requestMap = $this->convertRequestToMap();
        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();
        $requestMap["tf.enterprise_code"] = $user["enterprise_code"];
        //分页
        $count = $this->currentModel->getListCount($requestMap);
        $page = $this->page($count, C("DEFAULT_PAGE_SIZE"));

        //获取列表
        $list = $this->currentModel->queryForList($page, $requestMap);
//print_r($list);
//        $this->assign("statusEnum", C("DEFAULT_YN"));
        $this->assign('list', $list);
        $this->assign("user", $user);
        $this->assign("page", $page->show('Admin', $this->parameter));
        $this->display();

    }

    public function storageList() {
        $users_obj = M("admin");
        $userId = $_SESSION['ADMIN_ID'];
        $user = $users_obj->where("user_id=$userId")->find();
        $listStorage = D('Storage')->alias("sr")
            ->where(array('sr.enterprise_code'=>$user["enterprise_code"]))
            ->select();

        echo json_encode($listStorage);
    }

    public function claimTransfer() {
        $id = $_REQUEST["id"];
        $info = D("Transfer")->queryById($id);

        $users_obj = M("admin");
        $userId = $_SESSION['ADMIN_ID'];
        $user = $users_obj->where("user_id=$userId")->find();
        $claimAuditor = D("admin")->where(array('employee_id'=>$info["auditor_id"]))->find();
        $claimer = D("admin")->where(array('employee_id'=>$info["update_id"]))->find();

        $this->assign("claimer", $claimer);
        $this->assign("claimAuditor", $claimAuditor);

        if(isNullOrEmpty($info)){
            $enterprise = D("Enterprise")->where(array('enterprise_code'=>$user["enterprise_code"]))->find();
            $info["transfer_no"] = $enterprise["workorder_no_head"] . "TRANS-".date('Ymd',time()) . sprintf("%02d", substr(D("Transfer")->count(), -2, 2)+1);
            $info["update_id"] = $user["employee_id"];
        }

        $map["transfer_no"] = $info["transfer_no"];
        $list = D("TransferItem")->queryForList(null, $map);

        $listCode = D('Code')->alias("c")
            ->join("left join __CODE__ p on p.code_id = c.parentid")
            ->join("left join __MATERIAL__ m on m.code_id = c.code_id")
//            ->join("left join __STORAGE__ sr on sr.code_id = c.code_id")
            ->where(array('c.level' => 1, 'c.enterprise_code'=>$user["enterprise_code"]))
            ->field("c.*, c.name as code_name, p.name as parent_name, m.material_name")
            ->select();

        $listStorageMaterial = D('Storage')->alias("sr")
            ->join("left join __MATERIAL__ m on m.code_id = sr.code_id")
            ->join("left join __CODE__ c on c.code_id = sr.code_id")
            ->join("left join __CODE__ p on p.code_id = c.parentid")
            ->where(array('sr.type' => '物料', 'sr.enterprise_code'=>$user["enterprise_code"]))
            ->field("sr.*, c.name as code_name, p.name as parent_name, m.material_name, m.spec, m.prop, m.unit, m.barcode")
            ->select();

        $listFinishedProduct = D('FinishedProduct')->alias("fp")
            ->join("left join __CLASS__ cl on cl.class_id = fp.class_id")
            ->join("left join __SUPPLIER__ sl on sl.supplier_id = fp.supplier_id")
            ->where(array('fp.enterprise_code'=>$user["enterprise_code"]))
            ->order("fp.finished_product_id asc")
            ->field("fp.*, cl.class_name, sl.supplier_name")
            ->select();

        $listStorageFinishedProduct = D('Storage')->alias("sr")
            ->join("left join __FINISHED_PRODUCT__ fp on fp.finished_product_id = sr.finished_product_id")
            ->join("left join __CLASS__ cl on cl.class_id = fp.class_id")
            ->where(array('sr.enterprise_code'=>$user["enterprise_code"]))
//            ->order("fp.finished_product_id asc")
            ->field("sr.*, fp.finished_product_id, fp.class_id, fp.name as finished_product_name, fp.size_detail, fp.unit, fp.image_url, fp.number as code_name, cl.class_name")
            ->select();

        $listStorage = D('Storage')->alias("sr")
            ->where(array('sr.enterprise_code'=>$user["enterprise_code"]))
//            ->field("sr.*, c.name as code_name, p.name as parent_name, m.material_name, m.spec, m.prop, m.unit, m.barcode")
            ->select();

        $this->assign('info', $info);
        $this->assign('listCode', $listCode);
        $this->assign('listStorageMaterial', $listStorageMaterial);
        $this->assign('listFinishedProduct', $listFinishedProduct);
        $this->assign('listStorageFinishedProduct', $listStorageFinishedProduct);

        $this->assign("user", $user);
        $this->assign("list", $list);
        $this->assign("listStorage", $listStorage);
        $this->assign("row", count($list));
        $this->display("claimTransfer");
    }

    public function claimTransferPost() {
        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();
        $enterprise = D("Enterprise")->where(array('enterprise_code'=>$user["enterprise_code"]))->find();

        $id = $_REQUEST["id"];
        $data = D("Transfer")->queryById($id);
        if($_REQUEST["btnText"] == "调拨"){
            $transfer_no = $enterprise["workorder_no_head"] . "TRANS-".date('Ymd',time()) . sprintf("%02d", substr(D("Transfer")->count(), -2, 2)+1);

            if(isNullOrEmpty($id)){
                $data["transfer_no"] = $transfer_no;
                $data["enterprise_code"] = $user["enterprise_code"];
                $data["transfer_date"] = $_REQUEST["transfer_date"];
                $data["create_time"] = getCurrentDate();
                $data["transfer_id"] = $this->currentModel->add($data);
            }else{
                $transfer_no = $data["transfer_no"];
            }

            if(isNullOrEmpty($data["transfer_date"]))
                $data["transfer_date"] = getCurrentDate();
            $data["out_store_id"] = $_REQUEST["out_store_id"];
            $data["in_store_id"] = $_REQUEST["in_store_id"];
            $data["remark"] = $_REQUEST["remark"];
            $data["update_id"] = $user["employee_id"];
            $data["update_time"] = getCurrentDate();
            $data["status"] = -1;
            $this->currentModel->updateInfo($data);

            $oldList = D("TransferItem")->where(array('transfer_no'=>$data["transfer_no"]))->select();

            $row = $_REQUEST["row"];
            $idArr = array();
            for($i = 0; $i < $row; $i++){
                if(isNullOrEmpty($_REQUEST["code_id_".$i])){
                    continue;
                }
                $tmpData = null;
                $tmpData["transfer_item_id"] = $_REQUEST["transfer_item_id_".$i];
                $tmpData["type"] = $_REQUEST["type_".$i];
                $tmpData["transfer_no"] = $transfer_no;
                if($tmpData["type"] == "物料"){
                    $tmpData["code_id"] = $_REQUEST["item_id_".$i];
                }
                if($tmpData["type"] == "成品"){
                    $tmpData["finished_product_id"] = $_REQUEST["item_id_".$i];
                }
                $tmpData["size"] = $_REQUEST["size_".$i];
                $tmpData["batch_no"] = $_REQUEST["batch_no_".$i];
                $tmpData["number"] = $_REQUEST["number_".$i];
                $tmpData["price"] = $_REQUEST["price_".$i];
                $tmpData["production_date"] = $_REQUEST["production_date_".$i];
                if(isNullOrEmpty($tmpData["production_date"]))
                    $tmpData["production_date"] = getCurrentDate();
                $tmpData["expiry_date"] = $_REQUEST["expiry_date_".$i];
                if(isNullOrEmpty($tmpData["expiry_date"]))
                    $tmpData["expiry_date"] = getCurrentDate();
//                $tmpData["total_price"] = $_REQUEST["total_price_".$i];
                $tmpData["update_time"] = getCurrentDate();
                $tmpData["update_id"] = $user["employee_id"];
                if(isNullOrEmpty($tmpData["transfer_item_id"])){
                    $tmpData["create_time"] = getCurrentDate();
                    $tmpData["enterprise_code"] = $user["enterprise_code"];
                    D("TransferItem")->add($tmpData);
                }else{
                    D("TransferItem")->updateInfo($tmpData);
                    array_push($idArr, $tmpData["transfer_item_id"]);
                }
            }

            foreach ($oldList as $old){
                if (!in_array($old["transfer_item_id"], $idArr)) {
                    D("TransferItem")->deleteById($old["transfer_item_id"]);
                }
            }
            $this->success("调拨成功，单号：".$transfer_no, U("Transfer/index"));
        }
        if($_REQUEST["btnText"] == "审核"){
            $data["status"] = 1;
            $data["auditor_id"] = $user["employee_id"];
            $data["update_time"] = getCurrentDate();
            $this->currentModel->updateInfo($data);

            $List = D("TransferItem")->where(array('transfer_no'=>$data["transfer_no"]))->select();
            foreach ($List as $tmpData){
                $tmpData["out_store_id"] = $data["out_store_id"];
                $tmpData["in_store_id"] = $data["in_store_id"];
                $tmpStorage = D("Storage")
                    ->where(array('type'=>$tmpData["type"],
                        'enterprise_code'=>$user["enterprise_code"],
                        'code_id'=>$tmpData["code_id"],
                        'finished_product_id'=>$tmpData["finished_product_id"],
                        'store_id'=>$tmpData["store_id"],
                        'size'=>$tmpData["size"],
//                        'supplier_id'=>$tmpData["supplier_id"],
//                        'price'=>$tmpData["price"],
                        'batch_no'=>$tmpData["batch_no"]))
                    ->find();
                if(isNullOrEmpty($tmpStorage)){
                    $tmpData["storage_number"] = $tmpData["number"];
//                    $tmpData["code_id"] = $tmpData["code_id"];
                    D("Storage")->add($tmpData);
                }else{
                    $totalPrice = ($tmpStorage["price"] * $tmpStorage["storage_number"]) + ($tmpData["price"] * $tmpData["number"]);
                    $tmpStorage["storage_number"] += $tmpData["number"];
                    $tmpStorage["price"] = $totalPrice / $tmpStorage["storage_number"];
                    $tmpStorage["update_time"] = getCurrentDate();
                    $tmpStorage["update_id"] = $user["employee_id"];
                    D("Storage")->updateInfo($tmpStorage);
                }
                //计算平均成本
                $allItemList = D("Storage")
                    ->where(array('type'=>$tmpData["type"],
                        'enterprise_code'=>$user["enterprise_code"],
                        'code_id'=>$tmpData["code_id"],
                        'finished_product_id'=>$tmpData["finished_product_id"],
                        'store_id'=>$tmpData["store_id"],
                    ))
                    ->select();
                $totalItemPrice = 0;
                $totalItemNumber = 0;
                foreach ($allItemList as $tmpItem){
                    $totalItemPrice += ($tmpItem["price"] * $tmpItem["storage_number"]);
                    $totalItemNumber += $tmpItem["storage_number"];
                }
                $averagePrice = $totalItemPrice / $totalItemNumber;
                foreach ($allItemList as $tmpItem) {
                    $tmpItem["price"] = sprintf("%.2f", $averagePrice);
                    D("Storage")->updateInfo($tmpItem);
                }
            }

            $this->success("审核成功，单号：".$data["transfer_no"], U("Transfer/index"));
        }
        if($_REQUEST["btnText"] == "反审核"){
            $data["status"] = -2;
            $data["auditor_id"] = $user["employee_id"];
            $data["update_time"] = getCurrentDate();
            $this->currentModel->updateInfo($data);

            $List = D("TransferItem")->where(array('transfer_no'=>$data["transfer_no"]))->select();
            foreach ($List as $tmpData){
                $tmpData["store_id"] = $data["store_id"];
//                $tmpData["type"] = $tmpData["type"];
                $tmpStorage = D("Storage")
                    ->where(array('type'=>$tmpData["type"],
                        'enterprise_code'=>$user["enterprise_code"],
                        'code_id'=>$tmpData["code_id"],
                        'finished_product_id'=>$tmpData["finished_product_id"],
                        'store_id'=>$tmpData["store_id"],
                        'size'=>$tmpData["size"],
//                        'supplier_id'=>$tmpData["supplier_id"],
//                        'price'=>$tmpData["price"],
                        'batch_no'=>$tmpData["batch_no"]))
                    ->find();
                if(!isNullOrEmpty($tmpStorage)){
                    if($tmpStorage["storage_number"] == $tmpData["number"]){
                        D("Storage")->where(array("storage_id" => $tmpData["storage_id"]))->delete();
                    }else{
                        $totalPrice = ($tmpStorage["price"] * $tmpStorage["storage_number"]) - ($tmpData["price"] * $tmpData["number"]);
                        $tmpStorage["storage_number"] -= $tmpData["number"];
                        $tmpStorage["price"] = $totalPrice / $tmpStorage["storage_number"];
                        $tmpStorage["update_time"] = getCurrentDate();
                        $tmpStorage["update_id"] = $user["employee_id"];
                        D("Storage")->updateInfo($tmpStorage);
                    }
                }else{
                    $tmpData["store_id"] = $data["store_id"];
//                    $tmpData["code_id"] = $tmpData["code_id"];
//                    $tmpData["type"] = $tmpData["type"];
                    $tmpData["storage_number"] *= -1;
                    $tmpData["create_time"] = getCurrentDate();
                    $tmpData["update_time"] = getCurrentDate();
                    $tmpData["update_id"] = $user["employee_id"];
                    $tmpData["storage_number"] = $tmpData["number"];
                    D("Storage")->add($tmpData);
                }

                //计算平均成本
                $allItemList = D("Storage")
                    ->where(array('type'=>$tmpData["type"],
                        'enterprise_code'=>$user["enterprise_code"],
                        'code_id'=>$tmpData["code_id"],
                        'finished_product_id'=>$tmpData["finished_product_id"],
                        'store_id'=>$tmpData["store_id"],
                    ))
                    ->select();
                $totalItemPrice = 0;
                $totalItemNumber = 0;
                foreach ($allItemList as $tmpItem){
                    $totalItemPrice += ($tmpItem["price"] * $tmpItem["storage_number"]);
                    $totalItemNumber += $tmpItem["storage_number"];
                }
                $averagePrice = $totalItemPrice/$totalItemNumber;
                foreach ($allItemList as $tmpItem){
                    $tmpItem["price"] = sprintf("%.2f", $averagePrice);
                    D("Storage")->updateInfo($tmpItem);
                }
            }

            $this->success("反审核成功，单号：".$data["transfer_no"], U("Transfer/index"));
        }
    }
}